from flask import Blueprint, request, jsonify, g
from extensions import db
from models import Product, Category, Supplier, Inventory
from utils import success, error, bad_request, forbidden
from datetime import datetime

# 创建商品管理API蓝图
product_api = Blueprint('product_api', __name__, url_prefix='/api/products')

# 获取商品列表
@product_api.route('/', methods=['GET'])
def get_products():
    """获取商品列表"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('page_size', 10, type=int)  # 前端发送的是page_size
        search = request.args.get('search', '')
        category_id = request.args.get('category_id', type=int)
        supplier_id = request.args.get('supplier_id', type=int)
        status = request.args.get('status', '')
        
        # 构建查询
        query = Product.query
        
        # 搜索过滤
        if search:
            query = query.filter(
                Product.name.contains(search) 
            )
        
        # 分类过滤
        if category_id:
            query = query.filter(Product.category_id == category_id)
        
        # 供应商过滤
        if supplier_id:
            query = query.filter(Product.supplier_id == supplier_id)
        
        # 状态过滤
        if status:
            query = query.filter(Product.status == status)
        
        # 分页查询
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        products = []
        for product in pagination.items:
            # 获取库存信息
            inventory = Inventory.query.filter_by(product_id=product.id).first()
            stock_quantity = inventory.current_stock if inventory else 0
            
            product_data = {
                'id': product.id,
                'name': product.name,
                'sku': product.sku,
                'description': product.description,
                'category_id': product.category_id,
                'category_name': product.category.name if product.category else None,
                'supplier_id': product.supplier_id,
                'supplier_name': product.supplier.name if product.supplier else None,
                'unit_price': product.unit_price,
                'cost_price': product.cost_price,
                'unit': product.unit,
                'min_stock': product.min_stock,
                'max_stock': product.max_stock,
                'stock_quantity': stock_quantity,  # 添加库存数量
                'image': product.image,
                'status': product.status,
                'created_at': product.created_at.isoformat(),
                'updated_at': product.updated_at.isoformat()
            }
            products.append(product_data)
        
        return success(data={
            'products': products,
            'total': pagination.total,
            'pagination': {
                'page': pagination.page,
                'page_size': pagination.per_page,
                'total': pagination.total
            }
        }).to_response()
        
    except Exception as e:
        return error(msg=f'Failed to get product list: {str(e)}').to_response()

# 创建商品
@product_api.route('/', methods=['POST'])
def create_product():
    """创建新商品"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        # 检查请求是否为JSON格式
        if not request.is_json:
            return bad_request('请求必须是JSON格式').to_response()
        
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['name', 'sku', 'unit_price', 'cost_price', 'unit']
        for field in required_fields:
            if not data.get(field):
                return bad_request(msg=f'{field}字段不能为空').to_response()
        
        # 检查SKU是否已存在
        if Product.query.filter_by(sku=data['sku']).first():
            return bad_request(msg='商品编码已存在').to_response()
        
        # 创建商品
        product = Product(
            name=data['name'],
            sku=data['sku'],
            description=data.get('description', ''),
            category_id=data.get('category_id'),
            supplier_id=data.get('supplier_id'),
            unit_price=float(data['unit_price']),
            cost_price=float(data['cost_price']),
            unit=data['unit'],
            min_stock=int(data.get('min_stock', 0)),
            max_stock=int(data.get('max_stock', 1000)),
            image=data.get('image'),
            status=data.get('status', 'active')
        )
        
        db.session.add(product)
        db.session.commit()
        
        return success(data={'id': product.id}, msg='商品创建成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'Failed to create product: {str(e)}').to_response()


# 更新商品信息
@product_api.route('/<int:product_id>', methods=['PUT'])
def update_product(product_id):
    """更新商品信息"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        product = Product.query.get_or_404(product_id)
        
        # 检查请求是否为JSON格式
        if not request.is_json:
            return bad_request('请求必须是JSON格式').to_response()
        
        data = request.get_json()
        
        # 更新商品信息
        if 'name' in data:
            product.name = data['name']
        if 'sku' in data:
            # 检查SKU是否已被其他商品使用
            existing_product = Product.query.filter_by(sku=data['sku']).first()
            if existing_product and existing_product.id != product_id:
                return bad_request(msg='商品编码已存在').to_response()
            product.sku = data['sku']
        if 'description' in data:
            product.description = data['description']
        if 'category_id' in data:
            product.category_id = data['category_id']
        if 'supplier_id' in data:
            product.supplier_id = data['supplier_id']
        if 'unit_price' in data:
            product.unit_price = float(data['unit_price'])
        if 'cost_price' in data:
            product.cost_price = float(data['cost_price'])
        if 'unit' in data:
            product.unit = data['unit']
        if 'min_stock' in data:
            product.min_stock = int(data['min_stock'])
        if 'max_stock' in data:
            product.max_stock = int(data['max_stock'])
        if 'image' in data:
            product.image = data['image']
        if 'status' in data:
            product.status = data['status']
        
        product.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return success(msg='商品信息更新成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'Failed to update product: {str(e)}').to_response()

# 删除商品
@product_api.route('/<int:product_id>', methods=['DELETE'])
def delete_product(product_id):
    """删除商品"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        product = Product.query.get_or_404(product_id)
        
        # 检查是否有关联的库存记录
        if product.inventory_records:
            return bad_request(msg='该商品存在库存记录，无法删除').to_response()
        
        db.session.delete(product)
        db.session.commit()
        
        return success(msg='商品删除成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'Failed to delete product: {str(e)}').to_response()

